const app = getApp();
var home = require("../../utils/util.js");
var url = home.home;
var url2 = home.home2;
Page({
    /**
     * 页面的初始数据
     */
    data: {
      isShow:true,
      bgcolor: '',//ff7711
        bannerList: [],
        bannerData: {
            indicatorDots: true,
            vertical: false,
            autoplay: true,
            interval: 5000,
            duration: 500,
            indicator_color: '#fff',
            indicator_active_color: '#000',
        },
        videoData: {
            direction: -90,
            show_mute_btn: false,
            vslide_gesture: false,
        },
        shopData: {
            'storeName': '', //店铺名称
            'storePhone': '', //店铺手机号
            'storeVideo': '', //店铺视频,
            'lat': '', //纬度
            'lng': '', //经度
            'id': '', //店铺ID
            'businessEnd': '', //营业结束时间
            'businessStart': '', //营业开始时间
        }, //店铺信息
        imgShow: false, //图片预览
        bigImg: '',
        storeId: app.globalData.storeId, //店铺ID
        //storeId: '1551093550018179074', //王重阳
        loadImagePath: '',
        shopImg: [],
        shopVideoCover:[],
        shopVideoFile:[],
        states: false,
        states1: false,
        fileList: [{
                url: 'https://www.kyz66.com/fubaihui/sys/common/static/temp/六大特色功能介绍客宇宙版_01_1652286945215.png',
                name: '图片1'
            },
            {
                url: 'https://www.kyz66.com/fubaihui/sys/common/static/temp/六大特色功能介绍客宇宙版_01_1652286945215.png',
                name: '图片2'
            },
        ],
        storeVideo: home.getKey('storeVideo'),
        heights: 0,
        heights2: 0,
        scrollheight: 154,
        marginbottom: 100,
        locFlag:0,
        barTop: 0,
        barWith: 0,
    },
    onLoad: function () {
        var barWith = wx.getSystemInfoSync().screenWidth;
        var barTop = wx.getSystemInfoSync().statusBarHeight;//https://lequ7.com/guan-yu-xiao-cheng-xu-wei-xin-xiao-cheng-xu-zi-ding-yi-dao-hang-lan-yu-jiao-nang-dui-qi-fang-an.html
        let that = this;
        //console.log(barWith)
        // 高度自适应
        wx.getSystemInfo({
            success: function (res) {
                var clientHeight = res.windowHeight,
                    clientWidth = res.windowWidth,
                    rpxR = 750 / clientWidth;
                var calc = clientHeight * rpxR - 180;
                that.setData({
                    winHeight: calc,
                    barTop,
                    barWith,
                });
            }
        });
        if (home.getKey('hasNickName') && home.getKey('hasPhone')) {
            this.getTabBar().setData({
                state: 2
            });
            home.setKey('state',2);
        }
    },

    //删除图片
    deleteFile(e) {
        let fileList = this.data.fileList;
        fileList = fileList.splice(e.detail.index, 1);
        this.setData({
            fileList: fileList
        })
    },

    //上传图片
    afterRead(event) {
        let that = this;
        const {
            file
        } = event.detail;
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        wx.uploadFile({
            url: url + 'sys/common/upload', // 仅为示例，非真实的接口地址
            filePath: file.url,
            name: 'file',
            formData: {
                user: 'test'
            },
            success(res) {
                // 上传完成需要更新 fileList
                let fileList = that.data.fileList;
                fileList.push({
                    ...file,
                    url: res.data
                });
                that.setData({
                    fileList: fileList
                });
            },
        });
    },

    //显示图片预览弹出层
    showPopup2(e) {
        if (e.currentTarget.dataset.type == 1) {
            this.setData({
                imgShow: true,
                bigImg: e.currentTarget.dataset.imgs
            });
        }
    },

    //关闭图片预览弹出层
    onClose2() {
        this.setData({
            imgShow: false
        });
    },
    //获取地理位置显示标识
    getLocFlag(){
      let that = this;
      wx.request({
        url: url + 'app/getLocFlag',
        method: 'GET',
        header: {
                "content-type": "application/json", // 默认
            },
            success: function (res) {
              if (res.data.code == 200) {
                console.log(res.data);
                that.setData({
                  locFlag: res.data.result,
              })
              }
            }
      })
    },

    //获取店铺信息
    getShop() {
        let that = this;
        wx.request({
            url: url + 'app/getStore',
            data: {
                storeId: that.data.storeId
            },
            method: 'GET',
            header: {
                "content-type": "application/json", // 默认
            },
            success: function (res) {
                if (res.data.code == 200) {
                  console.log("storeBanner:" + res.data.result.storeBanner);
                    //res.data.result.storeBanner = res.data.result.storeBanner.split(',');
                    if(res.data.result.storeBanner != null && res.data.result.storeBanner != '' ){
                      res.data.result.storeBanner = res.data.result.storeBanner.split(',');
                    }
                    else{
                      res.data.result.storeBanner = '';
                    }
                    for (let i = 0; i < res.data.result.storeBanner.length; i++) {
                        res.data.result.storeBanner[i] = 'https://kyz.fbhkj.com//' + res.data.result.storeBanner[i];
                    }
                    if(res.data.result.storeVideo != null){
                      res.data.result.storeVideo = 'https://kyz.fbhkj.com//' + res.data.result.storeVideo;
                    }
                    
                    console.log("storeVideo:" + res.data.result.storeVideo);
                    console.log("storePhoto:" + res.data.result.storePhoto);
                    if(res.data.result.storePhoto != null){
                      res.data.result.storePhoto = res.data.result.storePhoto.split(',');
                    }

                    let shopImg = [];
                    if(res.data.result.storePhoto != null){
                      for (let i = 0; i < res.data.result.storePhoto.length; i++) {
                        let json = {};
                        json.file = 'https://kyz.fbhkj.com//' + res.data.result.storePhoto[i];
                        json.type = 1;
                        if (json.file.indexOf('png') == -1 && json.file.indexOf('jpg') == -1) {
                            json.file = 'https://kyz.fbhkj.com//' + res.data.result.storePhoto[i];
                            json.type = 2;
                        }
                        shopImg.push(json);
                        // res.data.result.storePhoto[i] = 'https://www.kyz66.com/fubaihui/sys/common/static/' + res.data.result.storePhoto[i];
                    }
                    }

                    let shopVideoCover = [];

                    if(res.data.result.storeVideoCover != null){
                      console.log(res.data.result.storeVideoCover);
                      res.data.result.storeVideoCover = res.data.result.storeVideoCover.split(',');
                      console.log(res.data.result.storeVideoCover);
                      for (let i = 0; i < res.data.result.storeVideoCover.length; i++) {
                        let json2 = {};
                          json2.file =  'https://kyz.fbhkj.com//'  + res.data.result.storeVideoCover[i];
                          json2.type = 1;
                          shopVideoCover.push(json2);
                          // res.data.result.storePhoto[i] = 'https://www.kyz66.com/fubaihui/sys/common/static/' + res.data.result.storePhoto[i];
                      }
                      console.log(shopVideoCover);
                    }

                    let shopVideoFile = [];

                    if(res.data.result.storeVideoFile != null){
                      res.data.result.storeVideoFile = res.data.result.storeVideoFile.split(',');
                      for (let i = 0; i < res.data.result.storeVideoCover.length; i++) {
                        let json3 = {};
                        json3.file =  'https://kyz.fbhkj.com//' + res.data.result.storeVideoFile[i];
                        json3.type = 1;
                        shopVideoFile.push(json3);
                        // res.data.result.storePhoto[i] = 'https://www.kyz66.com/fubaihui/sys/common/static/' + res.data.result.storePhoto[i];
                    }
                    }

                    console.log("storePhone"+res.data.result.storePhone);
                    home.setKey('stockPhoto', res.data.result.stockPhoto);
                    home.setKey('storePhone', res.data.result.storePhone);
                    home.setKey('bgcolor', res.data.result.colorTheme);
                    res.data.result.storeCity = res.data.result.storeCity.split(",");
                    res.data.result.storeCity = res.data.result.storeCity.join('');
                    home.setKey('storeCity', res.data.result.storeCity + res.data.result.storeAddress);
                    home.setKey('storeName', res.data.result.storeName);
                    home.setKey('lat', res.data.result.lat);
                    home.setKey('lng', res.data.result.lng);
                    if(Math.round((shopImg.length+shopVideoFile.length)/2)>2){
                        var scrollheight = 500;
                        var marginbottom = 160;
                    }else{
                        var scrollheight = Math.round((shopImg.length+shopVideoFile.length)/2)*154+100;
                        var marginbottom = 100;
                    }
                    that.setData({
                        scrollheight: scrollheight,
                        marginbottom: marginbottom,
                        shopData: res.data.result,
                        bannerList: res.data.result.storeBanner,
                        shopImg: shopImg,
                        bgcolor: res.data.result.colorTheme,
                        shopVideoCover:shopVideoCover,
                        shopVideoFile:shopVideoFile,
                    })
                } else {
                    home.wxMessage(res.data.message, 'none');
                }
            }
        })
    },

    official(e) {
        console.log(e);
    },

    /**
     * 调起手机拨号
     */
    callPhone() {
        let shopData = this.data.shopData;
        wx.makePhoneCall({
            phoneNumber: shopData.storePhone // 仅为示例，并非真实的电话号码
        })
    },

    /**
     * 打开地图
     */
    openMap() {
        if (this.data.shopData.lat == null) {
            home.wxMessage('店家信息不全!', 'none');
            return false;
        }
        // let that = this;
        // wx.getLocation({
        //     type: 'gcj02', //返回可以用于wx.openLocation的经纬度
        //     success(res) {
        //         let latitude = Number(that.data.shopData.lat);
        //         let longitude = Number(that.data.shopData.lng);
        //         console.log(latitude);
        //         console.log(longitude);
        //         wx.openLocation({
        //           type: 'gcj02',
        //           latitude: latitude,
        //           longitude: longitude,
        //           address: "",
        //           name:""
        //         })
        //     }
        // })
    },

    login() {
        wx.showLoading({
            title: '加载中...',
        });
        this.getTabBar().setData({
            btnState: false,
        });
        let that = this;
        wx.getUserProfile({
            desc: '用于完善会员资料',
            success: function (ress) {
                wx.login({
                    success: function name(res) {
                        wx.request({
                            url: url + 'app/xcx/updateUserNickName?storeId=' + app.globalData.storeId + '&code=' + res.code + '&nickName=' + ress.userInfo.nickName + '&headPortrait=' + ress.userInfo.avatarUrl + '&sex=保密' + '&unionId=' + home.getKey('unionId') + '&xcxOpenId=' + home.getKey('openId'),
                            data: {
                                code: res.code,
                                storeId: app.globalData.storeId,
                                nickName: ress.userInfo.nickName,
                                headPortrait: ress.userInfo.avatarUrl,
                                sex: '保密',
                                xcxOpenId: home.getKey('openId'),
                                unionId: home.getKey('unionId'),
                            },
                            method: 'POST',
                            header: {
                                "content-type": "application/json", // 默认
                            },
                            success: function (rea) {
                                if (rea.data.code == 200) {
                                    wx.hideLoading({
                                        success: (res) => {},
                                    })
                                    home.setKey('state', 2);
                                    that.getTabBar().setData({
                                        state: 2,
                                        btnState: true,
                                    });
                                    that.setData({
                                        states: false,
                                    })
                                    wx.reLaunch({
                                        url: '../index/index',
                                    })
                                }
                            }
                        })
                    }
                })
            },
            fail: function (params) {
                that.setData({
                    states: false,
                });
                that.getTabBar().setData({
                    btnState: true,
                });
            }
        })
    },

    onClose1() {
        this.setData({
            states: false,
        })
    },

    onClose3() {
        this.setData({
            states1: false
        });
    },
    // 点击封面自定义播放按钮时触发
 bindplay(e) {
  this.setData({
   isShow:false
  })
 
  this.videoContext = wx.createVideoContext('video'+e.currentTarget.dataset.content)
  console.log(e.currentTarget.dataset.content)
  this.videoContext.play();
  console.log('play')
 },

    register() {
        wx.showLoading({
            title: '加载中...',
        });
        let that = this;
        wx.login({
            success(res) {
                wx.request({
                    url: 'https://kyz.fbhkj.com/fubaihui/app/xcx/register?storeId=' + app.globalData.storeId + '&code=' + res.code,
                    data: {
                        storeId: app.globalData.storeId,
                        code: res.code
                    },
                    method: 'POST',
                    header: {
                        "content-type": "application/json", // 默认
                    },
                    success: function (rea) {
                        if (rea.data.code == 200) {
                            let states = false;
                            if (!rea.data.result.hasPhone) {
                                that.getTabBar().setData({
                                    state: 1
                                });
                                home.setKey('state', 1);
                                wx.setStorageSync('state', 1);
                            } else if (!rea.data.result.hasNickName) {
                                states = true;
                                that.getTabBar().setData({
                                    state: 0
                                });
                                home.setKey('state', 0);
                                wx.setStorageSync('state', 0);
                            }
                            home.setKey('subscribeTencent', rea.data.result.subscribeTencent);
                            home.setKey('hasNickName', rea.data.result.hasNickName);
                            home.setKey('hasPhone', rea.data.result.hasPhone);
                            home.setKey('userId', rea.data.result.member.id);
                            home.setKey('phone', rea.data.result.member.phone);
                            home.setKey('avatar', rea.data.result.member.avatarUrl);
                            home.setKey('status', rea.data.result.member.status);
                            home.setKey('discount', rea.data.result.member.discount);
                            home.setKey('nickName', rea.data.result.member.nickName);
                            home.setKey('openId', rea.data.result.member.xcxOpenId);
                            home.setKey('unionId', rea.data.result.member.unionId);
                            let states1 = false;
                            if (rea.data.result.hasPhone && rea.data.result.hasNickName) {
                                states1 = !rea.data.result.subscribeTencent;
                                that.getTabBar().setData({
                                    state: 2
                                });
                                home.setKey('state', 2);
                                wx.setStorageSync('state', 2);
                                that.getUserInfos();
                            }
                            that.setData({
                                states: states,
                                states1: states1,
                            })
                            wx.hideLoading({
                                success: (res) => {

                                },
                            })
                        } else {
                            home.wxMessage(rea.data.message, 'none');
                        }
                    }
                })
            }
        })
    },

    //获取用户数据
    getUserInfos() {
        wx.request({
            url: url + 'app/getUserInfo',
            data: {
                storeId: home.getKey('storeId'),
                phone: home.getKey('phone'),
                xcxOpenId: home.getKey('openId'),
            },
            method: 'GET',
            header: {
                "content-type": "application/json", // 默认
            },
            success: function (res) {
                if (res.data.code == 200) {
                    if (res.data.result.discount == null) {
                        res.data.result.discount = 10
                    }
                    if (res.data.result.balance == null) {
                        res.data.result.balance = 0;
                    }
                    if (res.data.result.stockLowest == null) {
                        res.data.result.stockLowest = 0;
                    }
                    if (res.data.result.equityBalance == null) {
                        res.data.result.equityBalance = 0;
                    }
                    if (res.data.result.totalDividend == null) {
                        res.data.result.totalDividend = 0;
                    }
                    if (res.data.result.equityTotal == null) {
                        res.data.result.equityTotal = 0;
                    }
                    home.setKey('discount', res.data.result.discount);
                    home.setKey('equityBalance', res.data.result.equityBalance);
                    home.setKey('balance', res.data.result.balance);
                    home.setKey('levelName', res.data.result.levelName);
                    home.setKey('stockLowest', res.data.result.stockLowest);
                    home.setKey('stockId', res.data.result.stockId);
                    home.setKey('birthday', res.data.result.birthday);
                    home.setKey('equityTotal', res.data.result.equityTotal);
                    home.setKey('nickName', res.data.result.nickName);
                    home.setKey('canWithdrawal', res.data.result.canWithdrawal);
                    home.setKey('noUseEquityBalancd', res.data.result.noUseEquityBalancd);
                    home.setKey('avatar', res.data.result.headProtrait);
                }
            }
        })
    },
//获取关注公众号url
getGzUrl(){
  wx.request({
    url: url + 'app/getGzUrl',
    data:{
      storeId:home.getKey('storeId')
    },
    method: 'GET',
    header: {
      "content-type": "application/json", // 默认
    },
    success:function (res) {
      if (res.data.code == 200) {
        if (res.data.result.gzUrl!= "") {
          home.setKey('gzUrl',res.data.result.gzUrl);
          console.log(home.getKey('gzUrl'));
        }
      } else {
        wx.showToast({
          title: '获取关注链接失败',
          icon: 'none'
        })
      }
    }
  })
},
    follow() {
        this.getGzUrl()
        wx.navigateTo({
            url: '../../shop/userInfo/gz',
        })
    },
    // openshipin() {
    //     wx.navigateTo({
    //         url: '../shipin/index?shipinid=1',
    //     })
    // },
    onCategory(event) {
      let url = event.currentTarget.dataset.url;
      //console.log(url);
      wx.switchTab({
        url: url
      });
    },

    onShow: function () {
        const updateManager = wx.getUpdateManager()
        updateManager.onCheckForUpdate(function (res) {
            // 请求完新版本信息的回调
            console.log(res.hasUpdate)
        });
        updateManager.onUpdateReady(function () {
            wx.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                success(res) {
                    if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate()
                    }
                }
            })
        })
        let that = this;
        setTimeout(function (params) {
            const query = wx.createSelectorQuery();
            query.select('#views').boundingClientRect(function (res) {
              that.setData({
                    heights: res.width
                })
            }).exec();
            query.select('#views2').boundingClientRect(function (res) {
              that.setData({
                  heights2: res.width
              })
          }).exec();
        }, 2000);
        this.getTabBar().setData({
            show3: false,
            show1: true,
            show2: false,
            show4: false,
        });
        home.setKey('storeId', this.data.storeId);
        this.getLocFlag();
        this.getShop();
        this.register();
        this.getGzUrl();
    },
     /**
   * 跳转订单列表
   */
  next_calculator(e){
    console.log(e.currentTarget.dataset.video)
    wx.navigateTo({
      url: '../video/index?video='+e.currentTarget.dataset.video,
    })
  },
    //分页
    onReachBottom: function () {

    },
    // 分享
    onShareAppMessage: function (ops) {

    },
    onReady: function (params) {

    },
    footerTap: app.footerTap
})